package com.mountainreacher.socketconnection;

import protocol.OnNewMessageListener;
import protocol.PairedConnection;
import communication.MessageDistpacher;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ChatActivity extends Activity implements OnNewMessageListener, OnClickListener {

	// Visual elements
	private EditText messageToSend;
	private EditText outputText;
	private Button sendButton;

	private PairedConnection pairedConnection;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);
		MessageDistpacher.INSTANCE.setListener(this);
		init();
	}

	private void init() {
		messageToSend = (EditText) findViewById(R.id.messageToSend);
		outputText = (EditText) findViewById(R.id.outputText);
		sendButton = (Button) findViewById(R.id.sendButton);
		sendButton.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.chat, menu);
		return true;
	}

	@Override
	public boolean onNewMessage(final String message) {
		runOnUiThread(new Runnable() {            
			@Override
			public void run() {
				outputText.setText(message+"\n"+outputText.getText());
				Toast.makeText(getApplicationContext(), message, 0).show();
			}
		});
		return true;
	}

	@Override
	public void getPairedConnection(PairedConnection connection) {
		this.pairedConnection = connection;
	}

	@Override
	public void onClick(View v) {
		if(messageToSend.length() > 0) {
			this.pairedConnection.sendMessage(messageToSend.getText().toString());
			messageToSend.setText("");
		}
	}

	@Override
	public void onCloseConnection() {
		runOnUiThread(new Runnable() {            
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), "Connection lost!", 0).show();
				finish();
			}
		});
	}

	@Override
	public void onBackPressed() {
		pairedConnection.closeConnection();
		super.onBackPressed();
	}

}
